package com.carl.guli.common.util;

import com.carl.guli.common.exception.BusinessException;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.Calendar;

/**
 * Created by youzm on 16/9/12.
 */
public class FileUploadUtil {
    /**
     * 根据路径和文件名生成File文件
     *
     * @param path
     * @param mFile
     * @return
     *
     * 2012-8-28
     */
    public static File getFileByPath(String path, CommonsMultipartFile mFile){
        if(mFile == null){
            return null;
        }
        // 获取当前时间的毫秒表示，作为文件名
        long countNumber = System.currentTimeMillis() ;
        // 获取当前上传文件的后缀名
        String suffix = mFile.getFileItem().getName().substring(mFile.getFileItem().getName().lastIndexOf("."));
        // 生成指定路径
        File parentPath = new File(path);
        // 如果指定路径不存在，生成指定路径
        if(!parentPath.exists()){
            parentPath.mkdirs();
        }
        return new File(parentPath, countNumber + RandomStringUtils.randomNumeric(4) + suffix);
    }

    public static String uploadImg(String path, CommonsMultipartFile mf) throws Exception {
        File file = null;
        String[] allowedType = { "image/bmp", "image/gif", "image/jpeg", "image/png" };

        boolean allowed = Arrays.asList(allowedType).contains(mf.getContentType());
        if (!allowed) {
            throw new BusinessException("error|不支持的类型");
        }
        // 图片大小限制
        if (mf.getSize() > 5 * 1024 * 1024) {
            throw new BusinessException("error|图片大小不能超过5M");
        }

        if (!mf.isEmpty()) {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            // 生成指定路径和指定名称的文件
            path = path + "/" + year + "" + month;

            file = FileUploadUtil.getFileByPath(path, mf);
            // 将上传的文件写入新建的文件中
            mf.getFileItem().write(file);
            // 文件名

            String fileName = year + "" + month + "/" + file.getName();
            return fileName;
        }

        return null;
    }
}
